package com.jprocms.module.cms.controller.portal.page;

import com.jprocms.module.cms.controller.portal.api.VoteApiController;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.dal.dataobject.vote.VoteDO;
import com.jprocms.module.cms.service.content.ContentCountService;
import com.jprocms.module.cms.service.site.SiteService;
import com.jprocms.module.cms.service.vote.VoteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 前台投票页面
 *
 * @author jprocms
 */
@Controller
public class VotePageController {

    private static final String TPL_INDEX = "sys/vote";
    private static final String TPL_DETAIL = "sys/vote_detail";
    private static final String TPL_RESULT = "sys/vote_result";

    @GetMapping({"/vote", "/{sitePath:[\\w-]+}/vote"})
    public String list(@PathVariable(required = false) String sitePath, HttpServletRequest request) {
        SiteDO site = siteService.getSite(sitePath);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_INDEX);
    }

    @GetMapping({"/vote/{id}", "/{sitePath:[\\w-]+}/vote/{id}"})
    public String show(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                       HttpServletRequest request, Map<String, Object> modelMap) {
        SiteDO site = siteService.getSite(sitePath);
        handleVote(id, modelMap);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_DETAIL);
    }

    @GetMapping({"/vote/{id}/result", "/{sitePath:[\\w-]+}/vote/{id}/result"})
    public String result(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                         Map<String, Object> modelMap) {
        SiteDO site = siteService.getSite(sitePath);
        handleVote(id, modelMap);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_RESULT);
    }

    private final ContentCountService contentCountService;
    private final SiteService siteService;
    private final VoteService service;

    public VotePageController(SiteService siteService, VoteService service, ContentCountService contentCountService) {
        this.siteService = siteService;
        this.service = service;
        this.contentCountService = contentCountService;
    }

    private void handleVote(Long id, Map<String, Object> modelMap) {
        VoteDO vote = service.getVote(id);
        VoteApiController.validateVote(id, vote);
        modelMap.put("vote", vote);
    }
}
